package com.kaluli.project.domain.entity;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class EntityConverter<T, M>
{
	private final Log log = LogFactory.getLog(getClass());
	
	/**
	 * 从VO对象转换为Model对象
	 * 
	 * @param modelClass
	 *            Model对象的Class对象
	 * @param valueBean
	 *            VO对象的实例
	 * @return Model对象的实例
	 * @throws Exception
	 */
	public T convertToModel(T model, M valueBean)
	{
		try
		{
			//将VO对象的属性复制到Model对象
			BeanUtils.copyProperties(model, valueBean);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return model;
	}
	
	/**
	 * 从VO对象集合转换为Model对象集合
	 * 
	 * @param modelClass
	 *            Model对象的Class对象
	 * @param valueBeans
	 *            VO对象集合
	 * @return Model对象集合
	 * @throws Exception
	 */
	public List<T> convertToModelList(Class<T> modelClass, List<M> valueBeans)
	{
		// 创建一个Model对象的集合
		List<T> models = new ArrayList<T>();
		// 将ValueBean对象集合中的元素填充到Model对象的集合
		for (M valueBean : valueBeans)
		{
			T model = null;
			try
			{
				model = modelClass.newInstance();
			}
			catch (Exception e)
			{
				e.printStackTrace();
				log.error(e.getMessage());
			}
			models.add(convertToModel(model, valueBean));
		}
		return models;
	}
	
	/**
	 * 从Model对象转换为VO对象
	 * 
	 * @param model
	 *            Model对象的实例
	 * @param valueBeanClass
	 *            VO对象的Class对象
	 * @return VO对象的实例
	 * @throws Exception
	 */
	public M convertFromModel(T model, M valueBean)
	{
		try
		{
			//将VO对象的属性复制到Model对象
			BeanUtils.copyProperties(valueBean, model);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			log.error(e.getMessage());
		}
		return valueBean;
	}
	
	/**
	 * 从Model对象集合转换为VO对象集合
	 * 
	 * @param models
	 *            Model对象集合
	 * @param valueBeanClass
	 *            ValueBean对象的Class对象
	 * @return VO对象集合
	 * @throws Exception
	 */
	public List<M> convertFromModelList(List<T> models, Class<M> valueBeanClass)
	{
		// 创建一个ValueBean对象的集合
		List<M> valueBeans = new ArrayList<M>();
		// 将Model对象集合中的元素填充到ValueBean对象的集合
		for (T model : models)
		{
			M valueBean = null;
			try
			{
				valueBean = valueBeanClass.newInstance();
			}
			catch (Exception e)
			{
				e.printStackTrace();
				log.error(e.getMessage());
			}
			valueBeans.add(convertFromModel(model, valueBean));
		}
		return valueBeans;
	}
	
}
